//
//  BCDatePickerController.m
//  Memo
//
//  Created by bonc on 13-9-5.
//  Copyright (c) 2013年 fuzhengbang. All rights reserved.
//

#import "BCDatePickerController.h"
#import "NSDate+Calendar.h"

@interface BCDatePickerController ()
@property (strong,nonatomic) UIDatePicker* myDatePicker;
@property (strong,nonatomic) UIPickerView* myTimePicker;
@property (strong,nonatomic) NSDate* minDate;
@property (strong,nonatomic) NSDate* maxDate;
@property (nonatomic)  BCDatePickType pickerType;
@end

@implementation BCDatePickerController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initTimeRangeFromDate:(NSDate*)beginTime   ToDate:(NSDate*)endTime WithType:(BCDatePickType)pickerType
{
    self=[super init];
    if (self) {
        if ([beginTime laterDate:endTime]) {
            _maxDate=beginTime;
            _minDate=endTime;
        }
        _minDate=beginTime;
        _maxDate=endTime;
        _pickerType=pickerType;
        _date=nil;
        self.title=@"选择时间";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    if (IOS_VERSION_Above_7_0) {
//        self.edgesForExtendedLayout=UIRectEdgeNone;
//    }
	// Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(done)];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancle)];
    
    self.view.backgroundColor=[UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.2f];
    
    if (self.pickerType==PickerTypeDate) {
        self.myDatePicker=[[UIDatePicker alloc]init];
        self.myDatePicker.backgroundColor=[UIColor clearColor];
        self.myDatePicker.datePickerMode=UIDatePickerModeDate;
        self.myDatePicker.minimumDate=self.minDate;
        self.myDatePicker.maximumDate=self.maxDate;
        self.myDatePicker.date=self.date;
        self.myDatePicker.center=CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-44);
        [self.view addSubview:self.myDatePicker];
            }else{
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents* comp=[[NSDateComponents alloc]init];
        [comp setHour:-8];
        self.maxDate=[gregorian dateByAddingComponents:comp toDate:self.maxDate options:0];
        self.minDate=[gregorian dateByAddingComponents:comp toDate:self.minDate options:0];
        self.myTimePicker=[[UIPickerView alloc]init];
        self.myTimePicker.delegate=self;
        self.myTimePicker.dataSource=self;
        [self.view addSubview:self.myTimePicker];
        self.myTimePicker.showsSelectionIndicator=YES;
        self.myTimePicker.center=CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-44);
        [self selectDate:self.date] ;
        }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Go Back Method
-(void)done
{
    if (self.pickerType==PickerTypeDate) {
        if (self.date!=self.myDatePicker.date) {
            NSDateComponents* comp=[[NSDateComponents alloc]init];
            [comp setHour:8];
            NSCalendar* cal=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
            NSDate* aDate=[cal dateByAddingComponents:comp toDate:self.myDatePicker.date options:0];
            self.date=aDate;
        }
        [self.delegate datePickerController:self   FinishedWithSelectedDate:self.date];
        NSLog(@"selectedDate=%@",self.date);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        if (self.date!=[self selectedDate]) {
            self.date=[self selectedDate];
        }
        [self.delegate datePickerController:self   FinishedWithSelectedDate:self.date];
        NSLog(@"selectedDate=%@",self.date);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)cancle
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark PickViewDelegate and PickerView Datasource Delegate
// returns the number of 'columns' to display.

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component==0) {
        return 80;
    }if (component==1||component==2) {
        return 60;
    }return 40;
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 5;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component==0) {
        return [[self arrayOfYear] count];
    }else if(component==1){
        NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
        NSInteger intYear=[yearStr integerValue];
        return [[self arrayOfMonthForYear:intYear] count];
    }else if (component==2){
        NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
        NSInteger intYear=[yearStr integerValue];
        
        NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
        NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
        NSInteger intMonth=[monthStr integerValue];
        
        return [[self arrayOfDayForYear:intYear Month:intMonth] count];
    }else if (component==3){
        NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
        NSInteger intYear=[yearStr integerValue];
        
        NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
        NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
        NSInteger intMonth=[monthStr integerValue];
        
        NSInteger dayIndex=[self.myTimePicker selectedRowInComponent:2];
        NSString* dayStr=[[self arrayOfDayForYear:intYear Month:intMonth] objectAtIndex:dayIndex];
        NSInteger intDay=[dayStr integerValue];
        
        return [[self arrayOfHourForYear:intYear Month:intMonth Day:intDay] count];
    }
    
    NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
    NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
    NSInteger intYear=[yearStr integerValue];
    
    NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
    NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
    NSInteger intMonth=[monthStr integerValue];
    
    NSInteger dayIndex=[self.myTimePicker selectedRowInComponent:2];
    NSString* dayStr=[[self arrayOfDayForYear:intYear Month:intMonth] objectAtIndex:dayIndex];
    NSInteger intDay=[dayStr integerValue];
    
    NSInteger hourIndex=[self.myTimePicker selectedRowInComponent:3];
    NSString* hourStr=[[self arrayOfHourForYear:intYear Month:intMonth Day:intDay] objectAtIndex:hourIndex];
    NSInteger intHour=[hourStr integerValue];
    return [[self arrayOfMinuteForYear:intYear Month:intMonth Day:intDay Hour:intHour] count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component==0) {
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:row];
        return [yearStr stringByAppendingString:@"年"];
    }else if(component==1){
        NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
        NSInteger intYear=[yearStr integerValue];
        
        NSString* monthStr=[[self arrayOfMonthForYear:intYear]objectAtIndex:row];
        return [monthStr stringByAppendingString:@"月"];
    }else if (component==2){
        NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
        NSInteger intYear=[yearStr integerValue];
        
        NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
        NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
        NSInteger intMonth=[monthStr integerValue];
        
        NSString* dayStr=[[self arrayOfDayForYear:intYear Month:intMonth] objectAtIndex:row];
        return [dayStr stringByAppendingString:@"日"];
    }else if (component==3){
        NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
        NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
        NSInteger intYear=[yearStr integerValue];
        
        NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
        NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
        NSInteger intMonth=[monthStr integerValue];
        
        NSInteger dayIndex=[self.myTimePicker selectedRowInComponent:2];
        NSString* dayStr=[[self arrayOfDayForYear:intYear Month:intMonth] objectAtIndex:dayIndex];
        NSInteger intDay=[dayStr integerValue];
        
        return [[self arrayOfHourForYear:intYear Month:intMonth Day:intDay] objectAtIndex:row];
    }
    NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
    NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
    NSInteger intYear=[yearStr integerValue];
    
    NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
    NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
    NSInteger intMonth=[monthStr integerValue];
    
    NSInteger dayIndex=[self.myTimePicker selectedRowInComponent:2];
    NSString* dayStr=[[self arrayOfDayForYear:intYear Month:intMonth] objectAtIndex:dayIndex];
    NSInteger intDay=[dayStr integerValue];
    
    NSInteger hourIndex=[self.myTimePicker selectedRowInComponent:3];
    NSString* hourStr=[[self arrayOfHourForYear:intYear Month:intMonth Day:intDay] objectAtIndex:hourIndex];
    NSInteger intHour=[hourStr integerValue];
    return [[self arrayOfMinuteForYear:intYear Month:intMonth Day:intDay Hour:intHour] objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component==0) {
        [self.myTimePicker reloadComponent:1];
        [self.myTimePicker reloadComponent:2];
        [self.myTimePicker reloadComponent:3];
        [self.myTimePicker reloadComponent:4];
    }else if (component==1){
        [self.myTimePicker reloadComponent:2];
        [self.myTimePicker reloadComponent:3];
        [self.myTimePicker reloadComponent:4];
    }else if(component==2){
        [self.myTimePicker reloadComponent:3];
        [self.myTimePicker reloadComponent:4];
    }else if(component==3){
        [self.myTimePicker reloadComponent:4];
    }
}
//#pragma mark -
//#pragma mark Utils Method

-(NSArray*)arrayOfYear
{
    return [self chageNumbersToStringsRangeFrom:[self.minDate year] To:[self.maxDate year]];
}

-(NSArray*)arrayOfMonthForYear:(NSInteger)year
{
    if (year==[self.minDate year]) {
        return  [self chageNumbersToStringsRangeFrom:[self.minDate month] To:12];
    }
    return [self chageNumbersToStringsRangeFrom:1 To:12];
}

-(NSArray*)arrayOfDayForYear:(NSInteger) year Month:(NSInteger)month
{
    NSInteger firstDay=1,lastDay=28;
    if ([self.minDate year]==year&&[self.minDate month]==month) {
        firstDay=[self.minDate day];
    }
    
    if (month==1||month==3||month==5||month==7||month==8||month==10||month==12) {
        lastDay=31;
    }else if (month==4||month==6||month==9||month==11) {
        lastDay=30;
    }else if(month==2){
        if ((year%4==0&&year%100!=0)||(year%100==0&&year%400==0)) {
            lastDay=29;
        }
    }
    return [self chageNumbersToStringsRangeFrom:firstDay To:lastDay];
}

-(NSArray*)arrayOfHourForYear:(NSInteger)year Month:(NSInteger)month Day:(NSInteger)day
{
    NSInteger firstHour=0;
    if ([self.minDate year]==year&&[self.minDate month]==month&&[self.minDate day]==day) {
        firstHour=[self.minDate hour];
    }
    return [self chageNumbersToStringsRangeFrom:firstHour To:23];
}

-(NSArray*)arrayOfMinuteForYear:(NSInteger)year Month:(NSInteger)month Day:(NSInteger)day
                           Hour:(NSInteger) hour
{
    NSInteger firstMinute=0;
    if ([self.minDate year]==year&&[self.minDate month]==month&&[self.minDate day]==day&&[self.minDate hour]==hour) {
        firstMinute=[self.minDate minute];
    }
    return [self chageNumbersToStringsRangeFrom:firstMinute To:59];
}

-(NSArray*)chageNumbersToStringsRangeFrom:(NSInteger) firstNumber To:(NSInteger)lastNumber
{
    NSMutableArray* strings=[[NSMutableArray alloc]init];
    for (NSInteger i=firstNumber; i<=lastNumber; i++) {
        NSString* string=[NSString stringWithFormat:@"%d",i];
        [strings addObject:string];
    }
    return strings;
}

-(NSDate*)selectedDate
{
    NSInteger yearIndex=[self.myTimePicker selectedRowInComponent:0];
    NSString* yearStr=[[self arrayOfYear] objectAtIndex:yearIndex];
    NSInteger intYear=[yearStr integerValue];
    
    NSInteger monthIndex=[self.myTimePicker selectedRowInComponent:1];
    NSString* monthStr=[[self arrayOfMonthForYear:intYear] objectAtIndex:monthIndex];
    NSInteger intMonth=[monthStr integerValue];
    
    NSInteger dayIndex=[self.myTimePicker selectedRowInComponent:2];
    NSString* dayStr=[[self arrayOfDayForYear:intYear Month:intMonth] objectAtIndex:dayIndex];
    NSInteger intDay=[dayStr integerValue];
    
    NSInteger hourIndex=[self.myTimePicker selectedRowInComponent:3];
    NSString* hourStr=[[self arrayOfHourForYear:intYear Month:intMonth Day:intDay] objectAtIndex:hourIndex];
    NSInteger intHour=[hourStr integerValue];
    
    NSInteger minuteIndex=[self.myTimePicker selectedRowInComponent:4];
    NSString* minuteStr=[[self arrayOfMinuteForYear:intYear Month:intMonth Day:intDay Hour:intHour] objectAtIndex:minuteIndex];
    NSInteger intMinute=[minuteStr integerValue];
    
    NSDate* date=[NSDate dateWithYear:intYear Month:intMonth Day:intDay Hour:intHour Minute:intMinute];
    return date;
}

-(void)selectDate:(NSDate*)aDate
{
    NSDate* initDate=aDate;
    if (initDate==nil) {
        NSAssert(0, @"cannot select a nil Date!");
    }
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    initDate=[gregorian dateByAddingComponents:comp toDate:initDate options:0];
    
    NSDateFormatter* fm=[[NSDateFormatter alloc]init];
    [fm setCalendar:[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]];
    [fm setLocale:[NSLocale currentLocale]];
    [fm setDateFormat:@"yyyy:MM:dd:HH:mm:ss"];
    NSString* timeStr=[fm stringFromDate:initDate];
    NSArray* timeCoponents=[timeStr componentsSeparatedByString:@":"];
    NSLog(@"date=%@,timeArray=%@",initDate,timeCoponents);
    
    NSString *yearStr,*monthStr,*dayStr,*hourStr,*minuteStr;
    yearStr=[timeCoponents objectAtIndex:0];
    monthStr=[timeCoponents objectAtIndex:1];
    dayStr=[timeCoponents objectAtIndex:2];
    hourStr=[timeCoponents objectAtIndex:3];
    minuteStr=[timeCoponents objectAtIndex:4];
    
    NSInteger yearIndex,monthIndex,dayIndex,hourIndex,minuteIndex;
    
    NSArray* yearArry=[self arrayOfYear];
    NSArray* monthArry=[self arrayOfMonthForYear:[yearStr integerValue]];
    NSArray* dayArray=[self arrayOfDayForYear:[yearStr integerValue] Month:[monthStr integerValue]];
    NSArray*hourArray=[self arrayOfHourForYear:[yearStr integerValue] Month:[monthStr integerValue] Day:[dayStr integerValue]];
    NSArray*minuteArray=[self arrayOfMinuteForYear:[yearStr integerValue] Month:[monthStr integerValue] Day:[dayStr integerValue] Hour:[hourStr integerValue]];
    
    yearIndex=[yearArry indexOfObject:yearStr];
    monthIndex=[monthArry indexOfObject:monthStr];
    dayIndex=[dayArray indexOfObject:[[NSString alloc] initWithFormat:@"%d",[dayStr integerValue]]];
    hourIndex=[hourArray indexOfObject:[[NSString alloc] initWithFormat:@"%d",[hourStr integerValue]]];
    minuteIndex=[minuteArray indexOfObject:[[NSString alloc] initWithFormat:@"%d",[minuteStr integerValue]]];
    
    [self.myTimePicker selectRow:yearIndex inComponent:0 animated:YES];
    [self.myTimePicker reloadComponent:1];
    [self.myTimePicker selectRow:monthIndex inComponent:1 animated:YES];
    [self.myTimePicker reloadComponent:2];
    [self.myTimePicker selectRow:dayIndex inComponent:2 animated:YES];
    [self.myTimePicker reloadComponent:3];
    [self.myTimePicker selectRow:hourIndex inComponent:3 animated:YES];
    [self.myTimePicker reloadComponent:4];
    [self.myTimePicker selectRow:minuteIndex inComponent:4 animated:YES];
}

@end
